import React, { useState } from 'react';
import { Button, Drawer } from 'antd';
import { Empty } from 'antd';
import './index.css';

// 模拟的数据
const productData = {
    id: 1,
    name: "【个性定制】T恤定制个人diy 情侣服 团建服 工装",
    basePrice: 120,
    images: [
        "https://pub-cdn-oss.chuangkit.com/print/show/266?version=1728278544717",
        "https://pub-cdn-oss.chuangkit.com/print/show/266_1?version=1728278544717",
        "https://pub-cdn-oss.chuangkit.com/print/show/266_2?version=1728278544717",
        'https://pub-cdn-oss.chuangkit.com/print/show/266_3?version=1728278544717',
        'https://pub-cdn-oss.chuangkit.com/print/show/266_4?version=1728278544717',
    ],
    addresses: ["北京", "天津", "上海"],
    styles: [
        { name: "220g纯棉(男女同款)", image: "https://pub-cdn-oss.chuangkit.com/print/show/266?version=1728278544717", price: 120 },
        { name: "240g纯棉(男女同款)", image: "https://pub-cdn-oss.chuangkit.com/print/show/266_1?version=1728278544717", price: 150 },
        { name: "圆领卫衣(男女同款)", image: "https://pub-cdn-oss.chuangkit.com/print/show/266_2?version=1728278544717", price: 180 },
        { name: "圆领卫衣(男女同款)", image: "https://pub-cdn-oss.chuangkit.com/print/show/266_3?version=1728278544717", price: 210 },
        { name: "圆领卫衣(男女同款)", image: "https://pub-cdn-oss.chuangkit.com/print/show/266_4?version=1728278544717", price: 240 },
    ],
    sizes: ["M", "L", "XL", "XXL", "XXXL"],
};

// 评价数据
const reviews = [
    {
        name: '北城',
        avatar: "https://pub-cdn-oss.chuangkit.com/userHead/52911969?imageMogr2/ignore-error/1/thumbnail/160x%3E?v=1653904542065",
        time: "2023-09-01",
        content: "非常满意，质量很好，值得购买！",
    },
    {
        name: '月光迟暮',
        avatar: "https://pub-cdn-oss.chuangkit.com/userHead/52911974?imageMogr2/ignore-error/1/thumbnail/160x%3E?v=1653904656748",
        time: "2023-09-02",
        content: "物流很快，衣服很合适。",
    },
    {
        name: '满心欢喜',
        avatar: "https://pub-cdn-oss.chuangkit.com/userHead/52911953?imageMogr2/ignore-error/1/thumbnail/160x%3E?v=1653902821320",
        time: "2023-09-03",
        content: "非常棒的购物体验，下次还会再来。",
    },
    {
        name: '人山人海',
        avatar: "https://pub-cdn-oss.chuangkit.com/userHead/52911978?imageMogr2/ignore-error/1/thumbnail/160x%3E?v=1653904963795",
        time: "2023-10-16",
        content: "客服态度很好，发货快包装完好，基本没有色差，裁剪完美",
    },
    {
        name: '花开富贵',
        avatar: "https://pub-cdn-oss.chuangkit.com/userHead/52912055?imageMogr2/ignore-error/1/thumbnail/160x%3E?v=1655919335742",
        time: "202-02-23",
        content: "质量很好，发货快，没有色差",
    },
    {
        name: '蓬莱',
        avatar: "https://pub-cdn-oss.chuangkit.com/userHead/52912099?imageMogr2/ignore-error/1/thumbnail/160x%3E?v=1655918353234",
        time: "2020-05-20",
        content: "质量没得说，物美价廉，好评，还会再次下单",
    },
    {
        name: '欺人太甚',
        avatar: "https://pub-cdn-oss.chuangkit.com/userHead/52912039?imageMogr2/ignore-error/1/thumbnail/160x%3E?v=1655919611507",
        time: "2019-11-30",
        content: "名片质量不错，软硬度适中。文字清晰。看起来有档次。物美价廉。值得购买",
    },
];

// 主详情页组件
const DetailPage: React.FC = () => {
    const [selectedImage, setSelectedImage] = useState(productData.images[0]);
    const [selectedStyle, setSelectedStyle] = useState(productData.styles[0]);
    const [totalPrice, setTotalPrice] = useState(selectedStyle.price * 10);
    const [hoveredStyle, setHoveredStyle] = useState<number | null>(null);
    const [lensPosition, setLensPosition] = useState<{ backgroundX: number; backgroundY: number } | null>(null);
    const [boxPosition, setBoxPosition] = useState<{ x: number; y: number } | null>(null);
    const [selectedSize, setSelectedSize] = useState<string | null>(null);
    const [selectedQuantity, setSelectedQuantity] = useState<number | null>(null);
    const [activeTab, setActiveTab] = useState('details');
    const [cartItems, setCartItems] = useState<any[]>([]);
    const [open, setOpen] = useState(false);
    const [selectedItems, setSelectedItems] = useState<{ [key: number]: boolean }>({});
    const [isAllSelected, setIsAllSelected] = useState(false);

    const zoomBoxSize = 200;
    const zoomFactor = 2;
    const [isZoomVisible, setIsZoomVisible] = useState(false);

    const showDrawer = () => {
        setOpen(true);
    };

    const onClose = () => {
        setOpen(false);
    };

    const handleMouseMove = (e: React.MouseEvent<HTMLImageElement>) => {
        const img = e.currentTarget;
        const { left, top, width, height } = img.getBoundingClientRect();
        const x = e.clientX - left;
        const y = e.clientY - top;

        let adjustedX = x - zoomBoxSize / 2;
        let adjustedY = y - zoomBoxSize / 2;

        if (adjustedX < 0) adjustedX = 0;
        else if (adjustedX + zoomBoxSize > width) adjustedX = width - zoomBoxSize;
        if (adjustedY < 0) adjustedY = 0;
        else if (adjustedY + zoomBoxSize > height) adjustedY = height - zoomBoxSize;

        setBoxPosition({ x: adjustedX, y: adjustedY });

        const backgroundX = (adjustedX / width) * (zoomFactor * 100);
        const backgroundY = (adjustedY / height) * (zoomFactor * 100);

        setLensPosition({ backgroundX, backgroundY });
    };

    const handleMouseEnter = () => {
        setIsZoomVisible(true);
    };

    const handleMouseLeave = () => {
        setLensPosition(null);
        setBoxPosition(null);
        setIsZoomVisible(false);
    };

    const handleQuantityChange = (quantity: number) => {
        setTotalPrice(selectedStyle.price * quantity);
        setSelectedQuantity(quantity);
    };

    const handleStyleChange = (style: { name: string; image: string; price: number }, index: number) => {
        setSelectedStyle(style);
        setSelectedImage(style.image);
        setTotalPrice(style.price * 10);
        setHoveredStyle(index);
    };

    const addToCart = () => {
        const newItem = {
            image: selectedImage,
            name: productData.name,
            style: selectedStyle.name,
            quantity: selectedQuantity,
            price: discountedPrice,
        };
        setCartItems(prevItems => [...prevItems, newItem]);
        setSelectedItems((prev) => ({ ...prev, [cartItems.length]: true }));
        setIsAllSelected(true);
        showDrawer();
    };

    const discountRate = 0.6;
    const discountedPrice = (totalPrice * discountRate).toFixed(2);
    const originalPrice = (totalPrice).toFixed(2);

    const totalPriceInCart = cartItems.reduce((total, item, index) => {
        return selectedItems[index] ? total + (parseFloat(item.price)) : total;
    }, 0).toFixed(2);
    const totalItemsInCart = cartItems.reduce((total, item, index) => {
        return selectedItems[index] ? total + item.quantity : total;
    }, 0);

    const toggleSelectAll = (isSelected: boolean) => {
        const updatedSelectedItems: any = {};
        cartItems.forEach((_, index) => {
            updatedSelectedItems[index] = isSelected;
        });
        setSelectedItems(updatedSelectedItems);
        setIsAllSelected(isSelected);
    };

    const toggleSelectItem = (index: number) => {
        setSelectedItems((prev) => ({
            ...prev,
            [index]: !prev[index],
        }));
        const allSelected = Object.values(selectedItems).every(item => item === true);
        setIsAllSelected(allSelected);
    };

    const deleteSelectedItems = () => {
        const newCartItems: any = cartItems.filter((_, index) => !selectedItems[index]);
        const newSelectedItems = { ...selectedItems };
        Object.keys(newSelectedItems).forEach((key: any) => {
            if (newCartItems.length <= key) {
                delete newSelectedItems[key];
            }
        });
        setCartItems(newCartItems);
        setSelectedItems(newSelectedItems);
        setIsAllSelected(false);
    };

    const renderContent = () => {
        switch (activeTab) {
            case 'details':
                return <p><img style={{ width: '100%', height: '95%' }} src="https://pub-cdn-oss.chuangkit.com/print/detail/67f2a555-438b-47d5-957b-5ada96f87804" alt="" /></p>;
            case 'reviews':
                return (
                    <div>
                        {reviews.map((review, index) => (
                            <div key={index} style={{ display: 'flex', alignItems: 'center', marginBottom: '15px', border: '1px solid #f0f0f0', padding: '10px', borderRadius: '5px' }}>
                                <img src={review.avatar} alt="Avatar" style={{ borderRadius: '50%', width: '40px', height: '40px', marginRight: '10px' }} />
                                <div>
                                    <p style={{ margin: '5px 0', fontWeight: 'bold' }}>{review.name}</p>
                                    <p style={{ margin: '5px 0', color: 'gray' }}>{review.time}</p>
                                    <p style={{ margin: '5px 0' }}>{review.content}</p>
                                </div>
                            </div>
                        ))}
                    </div>
                );
            case 'afterSale':
                return <p><img style={{ width: '100%', height: '95%' }} src="https://pub-cdn-oss.chuangkit.com/print/detail/87b63fd6-1813-4d71-a68b-ea08dca280fc" alt="" /></p>;
            case 'cases':
                return <p><img style={{ width: '100%', height: '95%' }} src="https://pub-cdn-oss.chuangkit.com/print/detail/8db5b4ee-e3e5-4521-a5eb-5d6c7d3c7334" alt="" /></p>;
            default:
                return null;
        }
    };

    return (
        <div style={{ position: 'relative', height: '2000px' }}>
            <div style={{ display: 'flex', position: 'absolute', left: '14%', top: '5%' }}>
                {/* 左侧商品图像 */}
                <div style={{ width: '400px', height: '400px' }}>
                    <div style={{ position: 'relative' }}>
                        <img
                            src={selectedImage}
                            alt="Product"
                            style={{ width: '100%', height: '100%', objectFit: 'contain' }}
                            onMouseMove={handleMouseMove}
                            onMouseLeave={handleMouseLeave}
                            onMouseEnter={handleMouseEnter}
                        />
                        {boxPosition && (
                            <div
                                className="zoom-box"
                                style={{
                                    left: boxPosition.x,
                                    top: boxPosition.y,
                                    width: zoomBoxSize,
                                    height: zoomBoxSize,
                                    border: '2px solid rgba(255, 255, 255, 0.5)',
                                    position: 'absolute',
                                }}
                            />
                        )}
                    </div>
                    {/* 缩略图 */}
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '10px' }}>
                        {productData.images.map((image, index) => (
                            <img
                                key={index}
                                src={image}
                                alt={`Thumb ${index}`}
                                style={{ width: '15%', cursor: 'pointer', marginLeft: '2%' }}
                                onMouseOver={() => setSelectedImage(image)}
                            />
                        ))}
                    </div>
                </div>

                {/* 放大镜 */}
                {isZoomVisible && lensPosition && (
                    <div
                        className="zoom-area"
                        style={{
                            width: '400px',
                            height: '400px',
                            position: 'absolute',
                            left: '35%',
                            backgroundImage: `url(${selectedImage})`,
                            backgroundSize: `${zoomFactor * 100}%`,
                            backgroundPosition: `${lensPosition.backgroundX}% ${lensPosition.backgroundY}%`,
                            border: '1px solid #ccc',
                        }}
                    />
                )}

                {/* 右侧商品详情 */}
                <div style={{ flex: 2, padding: '0 20px 20px 50px' }}>
                    <h2>{productData.name}</h2>
                    <div style={{ width: '100%', height: '40px', marginTop: '10px' }}>
                        <div style={{ float: 'left', lineHeight: '40px', marginRight: '15px', fontSize: '15px' }}>价格</div>
                        <div style={{ color: 'red', float: 'left', fontSize: '25px' }}> <b>¥ {discountedPrice}</b></div>
                        <div style={{ textDecoration: 'line-through', color: 'gray', float: 'left', lineHeight: '40px', fontSize: '15px', marginLeft: '5px' }}>¥ {originalPrice}</div>
                    </div>

                    {/* 全国地址 */}
                    <div style={{ width: '100%', height: '30px', lineHeight: '30px' }}>
                        <label style={{ float: 'left', }}>选择地址:</label>
                        <select>
                            {productData.addresses.map((address, index) => (
                                <option key={index} value={address}>{address}</option>
                            ))}
                        </select>
                    </div>

                    {/* 款式选择 */}
                    <div style={{ width: '65%', height: '110px', }}>
                        <div style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }}>
                            <label style={{ marginRight: '10px' }}>选择款式:</label>
                        </div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', cursor: 'pointer' }}>
                            {productData.styles.map((style, index) => (
                                <div
                                    key={index}
                                    style={{
                                        padding: '5px',
                                        margin: '3px',
                                        border: '1px solid',
                                        borderColor: hoveredStyle === index || selectedStyle === style ? 'blue' : 'gray',
                                        backgroundColor: hoveredStyle === index || selectedStyle === style ? 'lightblue' : 'transparent',
                                    }}
                                    onMouseEnter={() => setHoveredStyle(index)}
                                    onMouseLeave={() => setHoveredStyle(null)}
                                    onClick={() => handleStyleChange(style, index)}
                                >
                                    {style.name}
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* 尺码选择 */}
                    <div style={{ width: '70%', height: '110px' }}>
                        <label>选择尺码:</label><br />
                        {productData.sizes.map((size, index) => (
                            <button
                                key={index}
                                onClick={() => setSelectedSize(size)}
                                style={{
                                    width: '120px',
                                    height: '30px',
                                    margin: '5px',
                                    border: `2px solid ${selectedSize === size ? 'red' : 'gray'}`,
                                    backgroundColor: 'white',
                                    cursor: 'pointer',
                                    transition: 'border 0.3s',
                                }}
                                onMouseEnter={(e) => { e.currentTarget.style.border = '2px solid red'; }}
                                onMouseLeave={(e) => { if (selectedSize !== size) e.currentTarget.style.border = '2px solid gray'; }}
                            >
                                {size}
                            </button>
                        ))}
                    </div>

                    {/* 数量选择 */}
                    <div style={{ marginTop: '10px' }}>
                        <label>选择数量:</label>
                        {[10, 20, 50, 100].map((quantity) => (
                            <button
                                key={quantity}
                                onClick={() => handleQuantityChange(quantity)}
                                style={{
                                    width: '60px',
                                    height: '30px',
                                    margin: '5px',
                                    border: `2px solid ${selectedQuantity === quantity ? 'red' : 'gray'}`,
                                    backgroundColor: 'white',
                                    cursor: 'pointer',
                                    transition: 'border 0.3s',
                                }}
                                onMouseEnter={(e) => { e.currentTarget.style.border = '2px solid red'; }}
                                onMouseLeave={(e) => { if (selectedQuantity !== quantity) e.currentTarget.style.border = '2px solid gray'; }}
                            >
                                {quantity}
                            </button>
                        ))}
                    </div>

                    {/* 购买按钮 */}
                    <div style={{ width: '100%', height: '50px', marginTop: '15px' }}>
                        <button style={{ width: '180px', height: '40px', float: 'left', background: '#d7282d', border: '0', color: '#fff', borderRadius: '4px', marginRight: '50px' }}>立即购买</button>
                        <button style={{ width: '180px', height: '40px', float: 'left', background: '#fff', border: 'solid red 1px', color: 'red', borderRadius: '4px' }} onClick={addToCart}>加入购物车</button>
                    </div>
                </div>
            </div>

            {/* Tabs Section - 页面最底部 */}
            <div style={{ width: '72%', padding: '0', position: 'absolute', top: '30%', left: '14%', height: '60px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-around', backgroundColor: '#f9f9f9', padding: '0 60px 0 60px', borderRadius: '1px', height: '60px' }}>
                    <p onClick={() => setActiveTab('details')} style={{
                        backgroundColor: activeTab === 'details' ? 'white' : '#f9f9f9',
                        borderTop: activeTab === 'details' ? '2px solid red' : 'none',
                        cursor: 'pointer',
                        flexGrow: 1,
                        textAlign: 'center',
                        lineHeight: '60px',
                        fontWeight: 'bold',
                    }}>商品详情</p>
                    <p onClick={() => setActiveTab('reviews')} style={{
                        backgroundColor: activeTab === 'reviews' ? 'white' : '#f9f9f9',
                        borderTop: activeTab === 'reviews' ? '2px solid red' : 'none',
                        cursor: 'pointer',
                        flexGrow: 1,
                        textAlign: 'center',
                        lineHeight: '60px',
                        fontWeight: 'bold',
                    }}>商品评价</p>
                    <p onClick={() => setActiveTab('afterSale')} style={{
                        backgroundColor: activeTab === 'afterSale' ? 'white' : '#f9f9f9',
                        borderTop: activeTab === 'afterSale' ? '2px solid red' : 'none',
                        cursor: 'pointer',
                        flexGrow: 1,
                        textAlign: 'center',
                        lineHeight: '60px',
                        fontWeight: 'bold',
                    }}>售后问题</p>
                    <p onClick={() => setActiveTab('cases')} style={{
                        backgroundColor: activeTab === 'cases' ? 'white' : '#f9f9f9',
                        borderTop: activeTab === 'cases' ? '2px solid red' : 'none',
                        cursor: 'pointer',
                        flexGrow: 1,
                        textAlign: 'center',
                        lineHeight: '60px',
                        fontWeight: 'bold',
                    }}>案例展示</p>
                </div>
                <div style={{ width: '100%', height: '90%' }}>
                    {renderContent()}
                </div>
            </div>

            {/* 抽屉区域 */}
            <Drawer title="购物车" onClose={onClose} open={open} width={400}>
                <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                    <div style={{ flex: 1, overflowY: 'auto' }}>
                        {cartItems.length === 0 ? (
                            <Empty description='购物车暂无商品'
                                image="https://www.chuangkit.com/print/img/newEmptyCat.f1fae37a.png"
                                imageStyle={{ height: '120px' }} />
                        ) : (
                            <div>
                                <div style={{ display: 'flex', alignItems: 'center', marginBottom: '15px' }}>
                                    <input
                                        type="checkbox"
                                        checked={isAllSelected}
                                        onChange={(e) => toggleSelectAll(e.target.checked)}
                                        style={{ marginRight: '10px' }}
                                    />
                                    <label>全选</label>
                                    <Button type="link" onClick={deleteSelectedItems} style={{ marginLeft: 'auto' }}>批量删除</Button>
                                </div>
                                {cartItems.map((item, index) => (
                                    <div key={index} style={{ display: 'flex', alignItems: 'center', marginBottom: '15px', borderBottom: '1px solid #f0f0f0', padding: '10px' }}>
                                        <input
                                            type="checkbox"
                                            checked={selectedItems[index] || false}
                                            onChange={() => toggleSelectItem(index)}
                                            style={{ marginRight: '10px' }}
                                        />
                                        <img src={item.image} alt="Cart Item" style={{ width: '60px', height: '60px', marginRight: '10px' }} />
                                        <div style={{ flex: 1 }}>
                                            <p style={{ margin: '5px 0', fontWeight: 'bold' }}>{item.name}</p>
                                            <p style={{ margin: '5px 0' }}>款式: {item.style}</p>
                                            <p style={{ margin: '5px 0' }}>数量: {item.quantity}</p>
                                        </div>
                                        <p style={{ margin: '5px 0', color: 'red' }}>¥ {item.price}</p>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '20px' }}>
                        <p>总共{totalItemsInCart || 0}件</p>
                        <p>总价: ¥ {totalPriceInCart || 0}</p>
                    </div>
                    <Button type="primary" style={{ width: '100%', marginTop: '10px' }}>立即结算</Button>
                </div>
            </Drawer>
        </div>
    );
};

export default DetailPage;